﻿using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.Composition;
using System.Globalization;
using System.Linq;
using System.Web.Mvc;
using Fuse8.ContentManagementFramework.SystemFacade.Extensions;
using Fuse8.ContentManagementFramework.SystemFacade.Globalization;

namespace Fuse8.ContentManagementFramework.Administration.Models.MetaFields
{
    [MetaFieldValuesProvider]
    public class FreeListMetaFieldValuesProvider : IMetaFieldValuesProvider
    {
        public string Name
        {
            get
            {
                return "Predefined list of values";
            }
        }

        public string AdministrationViewName
        {
            get { return "metafields/customvalueseditor"; }
        }

        public bool CanAddItem
        {
            get { return false; }
        }

        public IEnumerable<CmsKeyValueItem> GetDataSource(string settings)
        {
            var list = settings.DigUpFromString<List<CmsKeyValueItem>>();

            return list;
        }

        public SelectListItem AddNewItem(string text, string settings)
        {
            return null;
        }

        public string GetSettings(ControllerContext modelState)
        {
            var binder = ModelBinders.Binders.GetBinder(typeof (List<CmsKeyValueItem>));
            var bindingContext = new ModelBindingContext()
                                     {
                                         ModelName = "Values",
                                         ValueProvider = modelState.Controller.ValueProvider,
                                         ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(()=>new List<CmsKeyValueItem>(), typeof(List<CmsKeyValueItem>))
                                     };
            var items = (binder.BindModel(modelState, bindingContext) as List<CmsKeyValueItem>) ??
                        new List<CmsKeyValueItem>();
            return items.Where(p => !string.IsNullOrEmpty(p.Value)).ToList().StoreMe();
        }

        public void SetSettings(ViewDataDictionary viewData, string settings)
        {
            try
            {
                var list = settings.DigUpFromString<List<CmsKeyValueItem>>();
                viewData["Values"] = list;
            }
            catch
            {
                
            }
        }
    }
}